﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace Studio.DocumentDB
{
    /// <summary>Helper class for handling code section raising errors.</summary>
    /// <remarks>Display error details to users.</remarks>
    public static class ErrorHelper
    {
        /// <summary>Handles an asynchronous code section.</summary>
        /// <param name="codeSection">Asynchronous code section.</param>
        /// <param name="windowChild">Child of a window ; the window will be used to display a message box.</param>
        /// <param name="errorFormat">Optional error formating.</param>
        /// <returns>Asynchronous completion:  <c>true</c> if no error was raised, <c>false</c> otherwise.</returns>
        public async static Task<bool> HandleAsync(
            Func<Task> codeSection,
            DependencyObject windowChild,
            string errorFormat = null)
        {
            if (windowChild == null)
            {
                throw new ArgumentNullException("windowChild");
            }
            if (codeSection == null)
            {
                throw new ArgumentNullException("codeSection");
            }
            if (string.IsNullOrWhiteSpace(errorFormat))
            {
                errorFormat = "{0}";
            }

            try
            {
                var task = codeSection();

                await task;

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    Window.GetWindow(windowChild),
                    string.Format(errorFormat, ex.Message),
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);

                return false;
            }
        }
    }
}